import 'package:adaptivex/adaptivex.dart';
import 'package:customer/extension/extension_widget.dart';
import 'package:customer/theme.dart';
import 'package:customer/utils/snackbar.dart';
import 'package:customer/widgets/gyy_dialog.dart';
import 'package:customer/widgets/gyy_theme.dart';
import 'package:fluent_ui/fluent_ui.dart';

import '../../constant/edit_constant.dart';
import '../../db/entity/AttributeBean.dart';
import '../../db/entity/ProductAttrBean.dart';
import '../../main.dart';
import '../../widgets/common/empty_data.dart';

class AddProductAttributePage extends StatefulWidget {
  final Map<String, dynamic> product;

  const AddProductAttributePage(this.product, {Key? key}) : super(key: key);

  @override
  State<AddProductAttributePage> createState() => _EditAttributeState();
}

class _EditAttributeState extends State<AddProductAttributePage> {
  var productAttrDao = database.productAttrDao; //产品属性

  var attributeDao = database.attributeDao;
  List<AttributeBean> allAttrList = []; //所有的属性
  List<AttributeBean> levelOneList = []; //一级属性
  List<AttributeBean> levelTwoList = []; //二级属性
  List<List<AttributeBean>> resultList = []; //二级联动属性
  Map<String, String> allAttrMap = {};

  TextEditingController attributeNameController = TextEditingController();
  TextEditingController attributeCodeController = TextEditingController();

  //该产品的所有属性
  List<ProductAttrBean> productAttributeList = [];

  //该产品的所有属性code - "p1", "1-1","1-2"
  List<String> productAttributeCodes = [];

  //选中的属性树集合
  Iterable<TreeViewItem>? selectTreeItems;
  Map<String, String> selectMap = {};

  initAttributeList() async {
    //所有属性
    allAttrList = await attributeDao.findAll();
    for (var element in allAttrList) {
      allAttrMap[element.attributeCode] = element.attributeName;
    }
    //组装二级联动数据
    levelOneList =
        allAttrList.where((element) => element.attributeLevel == 1).toList();
    levelTwoList =
        allAttrList.where((element) => element.attributeLevel == 2).toList();
    for (var one in levelOneList) {
      List<AttributeBean> oneList = [];
      for (var two in levelTwoList) {
        if (one.attributeCode == two.parentCode) {
          oneList.add(two);
        }
      }
      resultList.add(oneList);
    }
    debugPrint('所有属性-----' + allAttrList.length.toString());
  }

  //获取产品属性
  getProductAttribute() async {
    //改产品的所有属性
    productAttributeList =
        await productAttrDao.findByProductId(widget.product["id"]);
    //该产品的所有属性code
    productAttributeCodes =
        (productAttributeList.map((e) => e.attributeCode).toList());

    setState(() {});
  }

  saveProductAttribute(BuildContext context) async {
    if (selectTreeItems == null) {
      showMessage(context, StringConstant.dateNoChange);
      return;
    }
    selectMap = {};
    for (var element in selectTreeItems!) {
      selectMap[element.itemCode] = element.itemName;
    }
    var selectCodes = selectMap.keys;
    //产品原有的 && 未选中的 = 需要删除的
    var deleteList = [];
    for (var element in productAttributeCodes) {
      if (!selectCodes.contains(element)) {
        deleteList.add(element);
      }
    }
    //产品没有的 && 选中的 = 需要新增的
    var addList = [];
    for (var element in selectCodes) {
      if (!productAttributeCodes.contains(element)) {
        addList.add(element);
      }
    }
    debugPrint('删除=' + deleteList.toString());
    debugPrint('添加=' + addList.toString());
    if (addList.isEmpty && deleteList.isEmpty) {
      showMessage(context, StringConstant.dateNoChange);
      return;
    }
    String? res = await showContentDialog(context, "是否保存？");
    if (DialogConstant.ok == res) {
      //新增产品的属性
      if (addList.isNotEmpty) {
        List<ProductAttrBean> list = code2ProductAttrBean(addList);
        // debugPrint('插入=' + list.toString());
        await productAttrDao.insertList(list);
      }
      //删除产品的属性
      if (deleteList.isNotEmpty) {
        List<ProductAttrBean> list = productAttributeList
            .where((e) => deleteList.contains(e.attributeCode))
            .toList();
        // debugPrint('删除=' + list.toString());
        int count = await productAttrDao.deleteList(list);
        debugPrint('删除=' + count.toString());
      }

      getProductAttribute();
      showMessage(context, StringConstant.saveSuccess);
    }
  }

  //属性code集合 -> 产品属性集合
  List<ProductAttrBean> code2ProductAttrBean(List<dynamic> codes) {
    List<ProductAttrBean> list = [];
    for (var element in codes) {
      if (allAttrMap[element] != null) {
        ProductAttrBean bean = ProductAttrBean(
            productId: widget.product['id'],
            productCode: widget.product['productCode'],
            productName: widget.product['productName'],
            attributeId: 0,
            attributeCode: element,
            attributeName: allAttrMap[element]!,
            createTime: DateTime.now(),
            updateTime: DateTime.now());
        list.add(bean);
      }
    }
    return list;
  }

  @override
  void initState() {
    super.initState();
    //加载数据
    initAttributeList();
    getProductAttribute();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        padding: EdgeInsets.all(10),
        child: Container(
          child:
              //属性树
              levelOneList.isEmpty
                  ? emptyData(const Text('属性数据为空，请维护数据'))
                  : Row(
                      children: [
                        OutlinedButton(
                          style: ButtonStyle(
                            padding: ButtonState.all(EdgeInsets.zero),
                            backgroundColor: ButtonState.resolveWith((states) {
                              if (states.isPressing) {
                                return AppTheme.accentColor.withOpacity(0.3);
                              }
                              return AppTheme.accentColor.withOpacity(0.6);
                            }),
                          ),
                          onPressed: () async {
                            saveProductAttribute(context);
                          },
                          child: Container(
                              child: const Text("保存").padding(
                                  const EdgeInsets.symmetric(
                                      vertical: 5, horizontal: 10))),
                        ),
                        sizeBoxH10,
                        Expanded(
                          child: Card(
                            child: TreeView(
                              //部分选择
                              includePartiallySelectedItems: true,
                              selectionMode: TreeViewSelectionMode.multiple,
                              shrinkWrap: true,
                              items: buildItems(),
                              onSelectionChanged: (selectedItems) async {
                                //selectedItems就是选中的所有数据
                                selectTreeItems = selectedItems;
                                debugPrint(
                                    'onSelectionChanged: ${selectedItems.map((i) => i.itemCode)} - ${selectedItems.map((i) => i.itemName)}');
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
        ));
  }

  //构建item
  List<TreeViewItem> buildItems() {
    List<TreeViewItem> result = [];
    for (int i = 0; i < levelOneList.length; i++) {
      final one = levelOneList[i];
      var item = TreeViewItem(
        content: Text(one.attributeName),
        itemCode: one.attributeCode,
        itemName: one.attributeName,
        selected: productAttributeCodes.contains(one.attributeCode),
        children: buildSubItems(resultList[i]),
      );
      result.add(item);
    }
    return result;
  }

  //构建item
  List<TreeViewItem> buildSubItems(List<AttributeBean> wrapList) {
    return wrapList
        .map((two) => TreeViewItem(
              content: Text(two.attributeName),
              itemCode: two.attributeCode,
              itemName: two.attributeName,
              selected: productAttributeCodes.contains(two.attributeCode),
              children: [],
            ))
        .toList();
  }
}
